<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span{
            color: #aaa;
            font-size: 14px;
        }
        .right{
            color: green;
        }
        .wrong{
            color: red;
        }
    </style>
</head>
<body>
    <input type="text" class="uname"><span class="message">请输入用户名</span>
    <script>
        var reg=/^[a-zA-Z0-9_-]{6,16}/;
        // console.log(reg.test('a'));
        // console.log(reg.test('8'));
        // console.log(reg.test('18'));
        // console.log(reg.test('aa'));
        // console.log('------------------------');
        // console.log(reg.test('andy-red'));
        // console.log(reg.test('andy_red'));
        // console.log(reg.test('andy007'));
        // console.log(reg.test('andy!007'));
        
        var uname = document.querySelector('.uname');
        var span = document.querySelector('span');
        uname.onblur = function(){
            if(reg.test(this.value)){
                span.className='right';
                span.innerHTML = '用户名格式输入正确';
            }else{
                span.className = 'wrong';
                span.innerHTML = '用户名格式输入不正确';
            }
        }
    </script>
</body>
</html>